package sixyz.dao;

import sixyz.entity.User;
import sixyz.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO {

    private final JDBCUtils jdbcUtils = new JDBCUtils();
    private final BaseDAO<User> baseDAO = new BaseDAO<>();

    // 单实例
    private static final UserDAO userDAO = new UserDAO();
    private UserDAO() {}
    public static UserDAO getInstance() {
        return userDAO;
    }

    // 通过account查找用户
    public User queryUsersByAccount(String account) throws SQLException, ClassNotFoundException {
        Connection connection = jdbcUtils.getConnection();
        User user = null;
        String sqlStatement_selectSpecific = "SELECT * FROM user WHERE account = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sqlStatement_selectSpecific);
        preparedStatement.setString(1, account);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            String password = resultSet.getString("password");
            String nickname = resultSet.getString("nickname");
            String email = resultSet.getString("email");
            user = new User(account, password, nickname, email);
        }
        jdbcUtils.release(resultSet, preparedStatement, connection);
        return user;
    }

    public void insertUser(User user) throws SQLException, ClassNotFoundException, IllegalAccessException {
        baseDAO.save(user);
    }


}
